package com.cyz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.dao.CoursedesignDao;
import com.cyz.dao.HomeWorkDao;
import com.cyz.dao.TeacherDao;
import com.cyz.dao.UserDao;
import com.cyz.entity.CoursedesignEntity;
import com.cyz.entity.HomeWorkEntity;
import com.cyz.entity.TeacherEntity;
import com.cyz.entity.UserEntity;
import com.cyz.vo.HomeWorkDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("homeWork")
public class HomeWorkController {

    @Autowired
    HomeWorkDao homeWorkDao;

    @Autowired
    UserDao userDao;

    @Autowired
    TeacherDao teacherDao;

    @Autowired
    CoursedesignDao coursedesignDao;

    @RequestMapping("/list/{account}")
    public List<HomeWorkDto> list(@PathVariable String account){
        UserEntity entity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("account", account));

        TeacherEntity teacherEntity = teacherDao.selectOne(new QueryWrapper<TeacherEntity>().eq("name", entity.getName()));

        CoursedesignEntity coursedesignEntity = coursedesignDao.selectOne(new QueryWrapper<CoursedesignEntity>().eq("teacher_id", teacherEntity.getId()));

        List<HomeWorkEntity> homeWorkEntities = homeWorkDao.selectList(new QueryWrapper<HomeWorkEntity>().eq("course_id", coursedesignEntity.getId()));
        int i = 1;
        List<HomeWorkDto> result = new ArrayList<>();

        for (HomeWorkEntity workEntity : homeWorkEntities){
            HomeWorkDto homeWorkDto = new HomeWorkDto();
            homeWorkDto.setNo(i);
            homeWorkDto.setName(workEntity.getWork());
            i++;
            result.add(homeWorkDto);
        }
        return result;
    }

    @RequestMapping("/insert/{account}")
    public String insert(@PathVariable String account, String work){
        UserEntity entity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("account", account));

        TeacherEntity teacherEntity = teacherDao.selectOne(new QueryWrapper<TeacherEntity>().eq("name", entity.getName()));

        CoursedesignEntity coursedesignEntity = coursedesignDao.selectOne(new QueryWrapper<CoursedesignEntity>().eq("teacher_id", teacherEntity.getId()));

        HomeWorkEntity workEntity = new HomeWorkEntity();
        workEntity.setCourseName(coursedesignEntity.getId());
        workEntity.setWork(work);
        homeWorkDao.insert(workEntity);
        return "添加成功";
    }
}
